<template>
  <el-upload
    class="img-upload"
    ref="upload"
    action="http://localhost:7777/Content/Postcovers"
    accept="image/jpeg,image/gif,image/png"
    list-type = "picture-card"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    multiple
    :limit="1"
    :on-exceed="handleExceed"
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpeg/jpg/png文件，且不超过2M</div>
  </el-upload>
</template>

<script>
//图片上传
export default {
  name: "ImgUpload",
  data () {
    return {
      fileList: [],
      url: ''
    }
  },
  methods: {
    handleRemove (file, fileList) {
    },
    handlePreview (file) {
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    beforeUpload (file){
      const isJPEG = file.type === 'image/jpeg';
      const isJPG = file.type === 'image/jpg';
      const isPNG = file.type === 'image/png';
      const isPG = (isJPG || isPNG || isJPEG)
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPG) {
        this.$CustomMessage_ERROR('图片','上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$CustomMessage_ERROR('图片','上传文件大小不能超过 2MB!')
      }
      return isPG && isLt2M;
    },
    //文件上传成功的钩子
    handleSuccess (response) {
      if("2000" == response.msg){
        this.url = response.data;
        this.$emit('onUpload');
        this.$CustomMessage_OK('图片','上传成功');
      }
      else if("3000" == response.msg) this.$CustomMessage_WAENING('图片','图片格式错误！')
      else this.$CustomMessage_ERROR('图片','上传失败')
    },
    clear () {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped>

</style>
